package com.diy.sigmund.diygateway.filter;

import com.diy.sigmund.diycommon.entity.constant.GatewayConstant;
import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.support.WebContentGenerator;

/**
 * http://c.biancheng.net/view/5424.html
 * https://blog.csdn.net/huantai3334/article/details/108592137
 *
 * @author ylm-sigmund
 * @since 2021/9/4 10:44
 */
@Component
public class CustomLogFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(CustomLogFilter.class);

    /**
     * 返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     * pre：可以在请求被路由之前调用，在 Zuul 按照规则路由到下级服务之前执行。如果需要对请求进行预处理，比如鉴权、限流等，都应考虑在此类 Filter 实现。
     * route：在路由请求时候被调用，这类 Filter 是 Zuul 路由动作的执行者，是 Apache Http Client 或 Netflix Ribbon 构建和发送原始 HTTP 请求的地方，目前已支持 Okhttp。
     * post：在route和error过滤器之后被调用，这类 Filter 是在源服务返回结果或者异常信息发生后执行的，如果需要对返回信息做一些处理，则在此类 Filter 进行处理。
     * error：处理请求时发生错误时被调用，在整个生命周期内如果发生异常，则会进入 error Filter，可做全局异常处理。
     *
     * @return String
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * 通过int值来定义过滤器的执行顺序
     *
     * @return int
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_ERROR_FILTER_ORDER + 1;
    }

    /**
     * 返回一个boolean类型来判断该过滤器是否要执行，所以通过此函数可实现过滤器的开关。
     *
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     * Zuul 内部提供了一个动态读取、编译和运行这些 Filter 的机制。
     * Filter 之间不直接通信，在请求线程中会通过 RequestContext 来共享状态，它的内部是用 ThreadLocal 实现的，
     * 当然你也可以在 Filter之间使用 ThreadLocal 来收集自己需要的状态或数据。
     *
     * @return Object
     * @throws ZuulException ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        try {
            printRequestLog(request);
            return printResponseLog(request);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    private Object printResponseLog(HttpServletRequest request) {
        try {
            RequestContext currentContext = RequestContext.getCurrentContext();
            List<Pair<String, String>> originResponseHeaders = currentContext
                    .getOriginResponseHeaders();
            Map<String, String> zuulRequestHeaders = currentContext.getZuulRequestHeaders();

            List<Pair<String, String>> zuulResponseHeaders = currentContext
                    .getZuulResponseHeaders();
            boolean handleResBody = true;
            // 当contentType的值与自定义的相等时，不处理响应体
            for (Pair<String, String> zuulResponseHeader : zuulResponseHeaders) {
                if (Objects.equals("待自定义的contentType value", zuulResponseHeader.second())) {
                    handleResBody = false;
                    break;
                }
            }

            String resBody = handleResBody ? StreamUtils.copyToString(currentContext.getResponseDataStream(),
                    StandardCharsets.UTF_8) : "";

            // 长度大于16KB就不打印
            final int maxLength = 16 * 1024;
            if (resBody.length() > maxLength) {
                resBody = null;
            }
            StringBuilder sbRsp = new StringBuilder(1000);
            long costTime = Duration.between((LocalDateTime) currentContext.get(GatewayConstant.PRE_START_TIME),
                    LocalDateTime.now()).toMillis();
            sbRsp.append("\n-----------------------------网关层响应日志结束调用:-----------------------------\n");
            sbRsp.append("URI       : ").append(request.getMethod()).append(" ").append(request.getProtocol()).append(" ")
                    .append(request.getRequestURI()).append(buildParams(request)).append("\n");
            sbRsp.append("RequestBody    : ").append(buildBody(request)).append("\n");
            sbRsp.append("网关全局请求响应耗时  : ").append(costTime).append(" ms\n");
            sbRsp.append("ResponseBy    : ").append(resBody);
            log.info(sbRsp.toString());

            // 必须设置该值，否则响应为空
            currentContext.setResponseBody(resBody);
        } catch (IOException e) {
            log.error("", e);
        }
        return null;
    }

    private void printRequestLog(HttpServletRequest request) {
        String params = buildParams(request);
        // 获取请求体参数
        String body = buildBody(request);

        StringBuilder sb = new StringBuilder(1000);
        sb.append("\n-----------------------------网关层请求日志开始调用:-----------------------------\n");
        sb.append("URI       : ").append(request.getMethod()).append(" ").append(request.getProtocol()).append(" ")
                .append(request.getRequestURI()).append(params).append("\n");
        sb.append("Header    : {").append("\n");
        Enumeration<String> requestHeader = request.getHeaderNames();
        while (requestHeader.hasMoreElements()) {
            String headerKey = requestHeader.nextElement();
            // 打印所有Header值
            sb.append("    ").append(headerKey).append(" : ").append(request.getHeader(headerKey)).append("\n");
        }
        sb.append("}").append("\n");
        sb.append("RequestBody    : ").append(body);
        log.info(sb.toString());
    }

    public String buildBody(HttpServletRequest request) {
        RequestContext requestContext = RequestContext.getCurrentContext();
        String body = null;
        if (!requestContext.isChunkedRequestBody()) {
            try (ServletInputStream inp = requestContext.getRequest().getInputStream()) {
                if (inp != null) {
                    body = StreamUtils.copyToString(inp, StandardCharsets.UTF_8);
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }
        // 查询该请求是否是文件上传类型，如果是，则不打印
        boolean multipartContent = ServletFileUpload.isMultipartContent(request);
        if (multipartContent) {
            body = "当前接口为文件上传，不打印入参";
        }
        return body;
    }

    public String buildParams(HttpServletRequest request) {
        StringBuilder params = new StringBuilder("?");
        // 获取URL参数
        Enumeration<String> names = request.getParameterNames();
        if (request.getMethod().equals(WebContentGenerator.METHOD_GET) ||
                request.getMethod().equals(WebContentGenerator.METHOD_POST)) {
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                params.append(name);
                params.append("=");
                params.append(request.getParameter(name));
                params.append("&");
            }
        }
        if (params.length() > 0) {
            params.delete(params.length() - 1, params.length());
        }
        return params.toString();
    }
}
